package com.yunze.system.MemberGroup;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.yunze.apiCommon.mapper.mysql.YzCardRouteMapper;
import com.yunze.common.core.redis.RedisCache;
import com.yunze.common.mapper.mysql.YzExecutionTaskMapper;
import com.yunze.common.utils.yunze.WriteCSV;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class OutmemberGroup {

    @Resource
    private WriteCSV writeCSV;

    @Resource
    private com.yunze.common.mapper.mysql.memberGroup.memberGroupMapper memberGroupMapper;

    @Resource
    private RedisCache redisCache;

    @Resource
    private YzExecutionTaskMapper yzExecutionTaskMapper;

    @Resource
    private YzCardRouteMapper yzCardRouteMapper;

    @RabbitHandler
    @RabbitListener(queues = "admin_OutMemberGroup_queue")
    public void OutMemberGroupMethod(String msg, Channel channel) {
        try {
            if (StringUtils.isEmpty(msg)) {
                return;
            }
            Map<String, Object> Pmap = JSON.parseObject(msg);
            Map<String, Object> map = (Map<String, Object>) Pmap.get("map");//mapper查询用到的map
            String newName = Pmap.get("newName").toString();//newName 文件名
            List<Map<String, Object>> channel_code = (List<Map<String, Object>>) Pmap.get("channel_code");//通道
            List<Map<String, Object>> is_update = (List<Map<String, Object>>) Pmap.get("is_update");//是否修改
            List<Map<String, Object>> is_new = (List<Map<String, Object>>) Pmap.get("is_new");//是否新增
            String create_by = Pmap.get("create_by").toString();//create_by
            Map<String, Object> user = (Map<String, Object>) Pmap.get("User");//用户
            Map<String, Object> task_map = (Map<String, Object>) Pmap.get("task_map");//用户

            //获取通道信息
            Map<String, Object> find_simpleMap = new HashMap<String, Object>();
            find_simpleMap.putAll(map);
            find_simpleMap.put("cd_operator_type", null);//
            find_simpleMap.put("channel_id", null);//
            List<Map<String, Object>> routeArr = yzCardRouteMapper.find_simple(find_simpleMap);
            //获取 用户信息

            String prefix = "admin_OutMemberGroup_queue";
            //执行前判断 redis 是否存在 执行数据 存在时 不执行
            Object isExecute = redisCache.getCacheObject(prefix + ":" + create_by);
            if (isExecute == null) {
                redisCache.setCacheObject(prefix + ":" + create_by, "", 3, TimeUnit.SECONDS);//3 秒缓存 避免 重复消费

                OutFileMethod(routeArr, is_update, is_new, map, newName, user, task_map);

            }

        } catch (Exception e) {
            log.error(">>错误 - 连接管理导出 消费者:{}<<", e.getMessage().toString());
            e.printStackTrace();
        }

    }

    protected void OutFileMethod(List<Map<String, Object>> routeArr, List<Map<String, Object>> is_update,
                                 List<Map<String, Object>> is_new, Map<String, Object> map, String newName, Map<String, Object> user, Map<String, Object> task_map) {
        log.info("通道Arr{}",routeArr);
        try {
            List<Map<String, Object>> OutMGArr = memberGroupMapper.outChannel(map);

            //写入通道
            for (Map<String, Object> MGMap : OutMGArr) {

                MGMap = WriteCarRout(MGMap, routeArr);
                MGMap = WriteDic(MGMap, is_update, "inconsistent_iccid", "inconsistent_value");
                MGMap = WriteDic(MGMap, is_new, "is_new", "is_new_value");
            }
            Map<String, Object> Dept = (Map<String, Object>) user.get("dept");
            String agent_id = Dept.get("deptId").toString();

            if (agent_id.equals("100")) {
            }

            String Outcolumns[] = {"接入号", "iccid", "imsi", "激活时间", "开卡时间", "创建时间", "更新时间", "最近一次通道时间", "所属通道", "备注", "是否修改", "是否新增"};
            String keys[] = {"msisdn", "iccid", "imsi", "activate_date", "open_date", "create_date", "update_date", "syn_Time", "cd_name", "remark", "inconsistent_value", "is_new_value"};
            writeCSV.Write(newName, OutMGArr, Outcolumns, null, keys);
            yzExecutionTaskMapper.set_end_time(task_map);//任务结束
            log.info(">>>>>>>>>>>>>>>>>>创建结束<<<<<<<<<<<<<<<<<<");
        } catch (Exception e) {
            log.error("成员组导出错误:{}", e.getMessage());
        }

    }

    /**
     * 字典获取
     *
     * @param CarMap      写入Map
     * @param DictDataArr 字典 list
     * @param basis       获取依据 字段 与 dictValue 判断
     * @param fieldName   返回字段名称
     * @return
     */
    public Map<String, Object> WriteDic(Map<String, Object> CarMap, List<Map<String, Object>> DictDataArr, String basis, String fieldName) {

        Map<String, Object> Rmap = new HashMap<String, Object>();
        String status_id = CarMap.get(basis) != null ? CarMap.get(basis).toString() : null;
        boolean bool = false;
        if (status_id != null) {
            for (int i = 0; i < DictDataArr.size(); i++) {
                Map<String, Object> dictData = DictDataArr.get(i);
                String dictValue = dictData.get("dictValue").toString();
                if (dictValue.equals(status_id)) {
                    CarMap.put(fieldName, dictData.get("dictLabel"));
                    bool = true;
                    break;
                }
            }
        }
        //字段 默认值
        if (!bool) {
            CarMap.put(fieldName, "");
        }
        return CarMap;
    }

    /**
     * 写入 API 通道信息
     *
     * @param CarMap
     * @param routeArr
     * @return
     */
    protected Map<String, Object> WriteCarRout(Map<String, Object> CarMap, List<Map<String, Object>> routeArr) {

        Map<String, Object> Rmap = new HashMap<String, Object>();
        String channel_id = CarMap.get("channel_id") != null ? CarMap.get("channel_id").toString() : null;
        boolean bool = false;
        if (routeArr != null && channel_id != null) {
            for (int i = 0; i < routeArr.size(); i++) {
                Map<String, Object> RoutMap = routeArr.get(i);
                log.info("创建通道时的数据:RoutMap>{},CarMap>{}",RoutMap,CarMap);
                String cd_id = RoutMap.get("cd_id").toString();
                if (cd_id.equals(channel_id)) {
                    CarMap.put("cd_name", RoutMap.get("cd_alias"));
                    CarMap.put("dict_label", RoutMap.get("dict_label"));
                    bool = true;
                    break;
                }
            }
        }
        if (!bool) {
            CarMap.put("cd_name", "");
            CarMap.put("dict_label", "");
        }
        return CarMap;
    }
}
